package com.project.common;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

/**
 * 内存工厂，提供了访问内存，查找，组装memoryObject等的方法
 * 
 * @author HLJ
 * 
 */
public class MemoryFactory {
	public static String MEMORY_KEY = "MEMORY_KEY";

	/**
	 * 把object放到内存中去
	 * 
	 * @param memObject
	 * @param context
	 */
	public static void putMemoryObject(String key, MemoryObject memObject,
			ServletContext context) {
		Map map = null;
		Object obj = context.getAttribute(MEMORY_KEY);
		if (null == obj) {
			map = new HashMap<String, Object>();
			memObject.setCreatTime(new Date());
			map.put(key, memObject);
			context.setAttribute(MEMORY_KEY, map);
		} else {
			map = (Map) obj;
			// 设置放入资料的时间
			memObject.setCreatTime(new Date());
			map.put(key, memObject);
		}
	}

	/**
	 * 从内存中找到指定key的object
	 * 
	 * @param key
	 * @param context
	 */
	public static MemoryObject getMemoryObject(String key, long durSecond,
			ServletContext context) {
		//System.out.println("传入进来的值："+durSecond);
		//System.out.println(0==durSecond);
		if (0 == durSecond) {
			//System.out.println("2");
			//假如是限制时间是0，则直接返回null
			return null;
		}
		
		Object obj = context.getAttribute(MEMORY_KEY);
		if (null == obj) {
			return null;
		}
		Map map = (Map) obj;
		Object memoryObject = map.get(key);
		if (null == memoryObject) {
			return null;
		}
		// 假如找到，判读是否过期
		MemoryObject mo = (MemoryObject) memoryObject;
		if (MemoryFactory.isOverdue(mo.getCreatTime(), durSecond)) {
			return null;
		}
		return mo;
	}

	/**
	 * 返回当前时间和建立此资料的时间差 已秒计
	 * 
	 * @return
	 */
	public static long getDurSecond(Date date) {
		return (new Date().getTime() - date.getTime()) / 1000;
	}

	/**
	 * 判断是否过期
	 * 
	 * @param durSecond
	 *            过期的期限，以秒计
	 * @return
	 */
	public static boolean isOverdue(Date date, long durSecond) {
		if (durSecond > getDurSecond(date)) {
			return false;
		}
		return true;
	}
}
